package com.yunyi.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.validation.Validator;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunyi.common.constant.UserConstants;
import com.yunyi.common.core.domain.entity.SysOffice;
import com.yunyi.common.utils.SecurityUtils;
import com.yunyi.common.utils.file.Base64FileUtil;
import com.yunyi.common.utils.oss.AliyunOssFileUtils;
import com.yunyi.system.domain.SysUserRole;
import com.yunyi.system.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.yunyi.common.annotation.DataScope;
import com.yunyi.common.core.domain.entity.SysRole;
import com.yunyi.common.core.domain.entity.SysUser;
import com.yunyi.common.utils.StringUtils;
import com.yunyi.common.utils.spring.SpringUtils;
import com.yunyi.system.domain.SysPost;
import com.yunyi.system.service.ISysConfigService;
import com.yunyi.system.service.ISysUserService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 用户 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService
{
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired(required = false)
    private SysUserMapper userMapper;

    @Autowired(required = false)
    private SysRoleMapper roleMapper;

    @Autowired(required = false)
    private SysPostMapper postMapper;

    @Autowired(required = false)
    private SysOfficeMapper officeMapper;

    @Autowired(required = false)
    private SysUserRoleMapper userRoleMapper;

    @Autowired(required = false)
    private SysUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    protected Validator validator;

    @Autowired(required = false)
    private SysAdmininfoMapper admininfoMapper;

    @Autowired(required = false)
    private SysDoctorinfoMapper doctorinfoMapper;


    /**
     * 通过用户名查询用户
     * 
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName)
    {
        SysUser user = userMapper.selectUserByUserName(userName);
        if(StringUtils.isNotNull(user)){
            if (StringUtils.equals(user.getUser_type(), "2") || StringUtils.equals(user.getUser_type(), "3")){
                user.setSysDoctorinfo(doctorinfoMapper.selectDoctorInfoById(user.getUse_by()));
                return user;
            }
            user.setSysAdmininfo(admininfoMapper.selectAdminInfoById(user.getUse_by()));
        }
        return user;
    }

    /**
     * 查询用户所属角色组
     * 
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName)
    {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list))
        {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getName).collect(Collectors.joining(","));
    }

    /**
     * @Description: 查询用户所属机构
     * @Param [userName]
     * @Return java.util.List<com.yunyi.system.domain.SysOffice>
     * @Throws
     **/
    @Override
    public String selectOfficesByUserName(String userName){
        List<SysOffice> list = officeMapper.selectOfficesByUserName(userName);
        if (CollectionUtils.isEmpty(list)){
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysOffice::getName).collect(Collectors.joining("-"));
    }

    /**
     * 校验用户名称是否唯一
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getId()) ? -1L : user.getId();
        SysUser info = userMapper.checkUserNameUnique(user.getLogin_name());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getId()) ? -1L : user.getId();
        SysUser info = userMapper.checkPhoneUnique(user.getMobile());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getId()) ? -1L : user.getId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 修改用户基本信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     * 
     * @param userName 用户名
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar)
    {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     * 
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password)
    {
        return userMapper.resetUserPwd(userName, password, SecurityUtils.getUsername());
    }

    /**
     * @Description: 条件分页查询用户信息
     * @Param [pageNum, pageSize, user]
     * @Return com.baomidou.mybatisplus.core.metadata.IPage<com.yunyi.common.core.domain.entity.SysUser>
     * @Throws
     **/
    @Override
    public IPage<SysUser> selectUserList(Integer pageNum, Integer pageSize, SysUser user) {
        Page<SysUser> page = new Page<>(pageNum, pageSize);
        return userMapper.selectUserList(page, user);
    }

    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        return null;
    }

    /**
     * @Description: 修改用户信息
     * @Param [user]
     * @Return java.lang.Boolean
     * @Throws
     **/
    @Override
    @Transactional
    public Boolean updateUserInfo(SysUser user) {
        // 修改用户与角色信息
        userRoleMapper.deleteUserRoleByUserId(user.getId().longValue());
        List<SysUserRole> userRoles = new ArrayList<>();
        for (Long item : user.getRoleIds()) {
            userRoles.add(new SysUserRole(user.getId().longValue(), item));
        }
        userRoleMapper.batchUserRole(userRoles);

        // 处理用户头像
        if (user.getPhoto().indexOf("base64") != -1) {
            MultipartFile multipartFile = Base64FileUtil.base64ToMultipart(user.getPhoto());
            try {
                String photo = AliyunOssFileUtils.uploadFile(multipartFile);
                user.setPhoto(photo);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 处理用户密码
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));

        // 处理字段信息
        user.setUpdateBy(SecurityUtils.getUsername());
        user.setUpdateTime(new Date());
        return userMapper.updateById(user) > 0;
    }

    /**
     * @Description: 新增用户信息
     * @Param [user]
     * @Return java.lang.Boolean
     * @Throws
     **/
    @Override
    @Transactional
    public Boolean addUserInfo(SysUser user) {
        // 处理头像
        if (StringUtils.isNotNull(user.getPhoto())) {
            try {
                MultipartFile file = Base64FileUtil.base64ToMultipart(user.getPhoto());
                user.setPhoto(AliyunOssFileUtils.uploadFile(file));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 处理密码
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));

        // 处理字段信息
        user.setCreateBy(SecurityUtils.getUsername());
        user.setCreateTime(new Date());
        user.setUpdateBy(SecurityUtils.getUsername());
        user.setUpdateTime(new Date());
        // 添加角色
        int result = userMapper.insert(user);

        // 处理角色添加
        List<SysUserRole> userRoles = new ArrayList<>();
        for (Long roleId : user.getRoleIds()) {
            userRoles.add(new SysUserRole(user.getId().longValue(), roleId));
        }
        int rows = userRoleMapper.batchUserRole(userRoles);

        return result > 0 && rows == user.getRoleIds().length;
    }

    /**
     * @Description: 查询被分配该角色的用户
     * @Param []
     * @Return com.baomidou.mybatisplus.core.metadata.IPage<com.yunyi.common.core.domain.entity.SysUser>
     * @Throws
     **/
    @Override
    public IPage<SysUser> allocatedUserList(SysUser user, Integer pageNum, Integer pageSize) {
        Page<SysUser> page = new Page<>(pageNum, pageSize);
        IPage<SysUser> userPage = userMapper.allocatedUserList(page, user);
        return userPage;
    }

    /**
     * @Description: 查询未被分配该角色的用户
     * @Param []
     * @Return com.baomidou.mybatisplus.core.metadata.IPage<com.yunyi.common.core.domain.entity.SysUser>
     * @Throws
     **/
    @Override
    public IPage<SysUser> unAllocatedUserList(SysUser user, Integer pageNum, Integer pageSize) {
        Page<SysUser> page = new Page<>(pageNum, pageSize);
        IPage<SysUser> userPage = userMapper.unAllocatedUserList(page, user);
        return userPage;
    }

    @Override
    public List<SysUser> findUsers(String jobName) {
        return userMapper.findUsers(jobName);
    }

}
